import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/class_db_provider.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/class/model/class_c_model.dart';
import 'package:flutter_douban/main_page/class/model/class_item_model.dart';
import 'package:flutter_douban/main_page/class/model/class_list_model.dart';
import 'package:flutter_douban/main_page/class/view/class_category_view.dart';
import 'package:flutter_douban/main_page/class/view/class_cell_view.dart';
import 'package:flutter_douban/main_page/class/view/class_header_view.dart';
import 'package:flutter_douban/main_page/class/view/class_nav_view.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/main_page/class/model/class_big_model.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';

class ClassRoomPage extends StatefulWidget {
  const ClassRoomPage({Key? key}) : super(key: key);

  @override
  _ClassRoomPageState createState() => _ClassRoomPageState();
}

class _ClassRoomPageState extends State<ClassRoomPage> {
  /// 推荐数据
  List<ClassListModel> _recommend_course = [];
  /// 本地缓存的数据
  List<ClassItemModel> _classList = [];
  /// 本地缓存的数据id
  List<String> _idList = [];
  /// 列表数据
  List<ClassCModel> _list = [];

  /// 控制器
  EasyRefreshController? _easyRefreshController;
  StreamSubscription<LoginEvent>? _loginSubscription;

  Future<void> _getData() async {
    _idList = [];
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    ClassDbProvider provider = new ClassDbProvider();
    Database db = await provider.getDataBase();
    List<Map<String, dynamic>> maps =
    await db.rawQuery("select * from ${provider.name} where ${provider.phoneNum} = $numberId order by ${provider.time} desc");
    ClassItemModelList noteModelList = ClassItemModelList.fromJson(maps);
    setState(() {
      _classList = noteModelList.list;
      for(int i = 0; i< _classList.length;i++){
        ClassItemModel itemModel = _classList[i];
        _idList.add(itemModel.id!);
      }
      _getRecommendData();
    });
  }

  /// 获取数据
  Future _getRecommendData() async {
    try {
      /// 全部数据
      Map<String, dynamic> result =
          await HttpService.getMockDataWithPath(path: 'mock/class_list.json');
      /// 轮播图数据
      ClassBigModel classBigModel = ClassBigModel.fromJson(result['result']);
      setState(() {
        _recommend_course = classBigModel.recommend_course!;
        _list = classBigModel.list!;
        /// 查询数据库中已经收藏
        for (int i = 0 ;i < _recommend_course.length;i++){
          ClassListModel listModel = _recommend_course[i];
          for(int j = 0 ;j < listModel.courses!.length;j++){
            ClassItemModel itemModel = listModel.courses![j];
            if(_idList.contains(itemModel.id)){
              itemModel.is_collection = true;
            }else{
              itemModel.is_collection = false;
            }
          }
        }
        for (int i = 0 ;i < _list.length;i++){
          ClassCModel classCModel = _list[i];
          if(_idList.contains(classCModel.c!.id!)){
            classCModel.c!.is_collection = true;
          }else{
            classCModel.c!.is_collection = false;
          }
        }
      });

      /// 结束加载状态
      _easyRefreshController!.resetLoadState();
      _easyRefreshController!.finishLoad(noMore: true);
    } catch (e) {
      print(e);
    } finally {}
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        _getData();
      });
    });
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    Widget widget;
    if (_recommend_course.length > 0 && _list.length > 0) {
      List<Widget> widgetList = [];
      widgetList.add(
        ClassCategoryView(),
      );
      _recommend_course.forEach((element) {
        widgetList.add(ClassHeaderView(model: element));
      });

      widgetList.add(Container(
        padding: EdgeInsets.only(left: 20, bottom: 6),
        alignment: Alignment.centerLeft,
        child: Text("全部课程",
            style: TextStyle(
                fontSize: 20,
                color: Colors.black,
                fontWeight: FontWeight.bold)),
      ));

      widgetList.add(Container(
        color: AppColors.page,
        padding: EdgeInsets.only(left: 14, right: 14, top: 10),
        child: GridView.builder(
            itemCount: _list.length,
            primary: false,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //横轴元素个数
                crossAxisCount: 2,
                //纵轴间距
                mainAxisSpacing: 1.0,
                //横轴间距
                crossAxisSpacing: 10.0,
                //子组件宽高长度比例
                childAspectRatio: 0.53),
            itemBuilder: (BuildContext context, int index) {
              return ClassCellView(
                model: _list[index],
              );
            }),
      ));

      widget = EasyRefresh(
          firstRefresh: false,
          header: CustomHeaderView(),
          controller: _easyRefreshController,
          enableControlFinishRefresh: false,
          enableControlFinishLoad: true,
          onRefresh: _getData,
          child: Column(
            children: widgetList,
          ));
    } else {
      widget = StancePage();
    }

    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: ClassNavView(),
        ),
        body: widget);
  }
}
